import os
import argparse
import pandas as pd
from openai import OpenAI

KEY="xxxxxxxxxxxxxxxxxxxx"
# URL="https://api.moonshot.cn/v1"
# MODEL="moonshot-v1-8k"
URL="https://dashscope.aliyuncs.com/compatible-mode/v1"
MODEL="qwen-turbo"

client = OpenAI( api_key = KEY, base_url = URL )

def translate(txt:str)->str:
    completion = client.chat.completions.create(
        model = MODEL,
        messages = [
            {"role": "system", "content": "你是一个专业翻译，你要把我接下来写的内容，分别翻译成英语、法语和日语。每种翻译之间，用|||来分隔"},
            {"role": "user", "content": txt}
        ],
        temperature = 0.3,
    )    
    return completion.choices[0].message.content
    
def save_progress(df, file):
    df.to_excel(file, index=False)

def is_file_opened(file):
    try:
        with open(file, 'a') as fp:
            pass
        return False
    except IOError:
        return True

def run(infile, outfile, fromLang, max_errcnt, startRow, saveInterval):    
    err_cnt = 0
    entry_cnt = 0
    df = pd.read_excel(infile)
    for i, txt in enumerate(df[fromLang][startRow-2:], startRow-2):
        try:
            ret = translate(txt)
            translated = ret.split("|||")
            df.loc[i, 'English'] = translated[0]
            df.loc[i, 'French'] = translated[1]
            df.loc[i, 'Japanese'] = translated[2]
            print(f"已翻译 Row{i+2}")
        except Exception as e:
            print(f"翻译出错：Row{i+2}: {e}")
            err_cnt += 1
            if err_cnt >= max_errcnt:
                save_progress(df, "tmp.xlsx")
                return
            
        entry_cnt += 1
        if entry_cnt % saveInterval == 0:
            save_progress(df, "tmp.xlsx")

    # end, save to output file
    save_progress(df, outfile)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", required=True, help="输入excel文件路径")
    parser.add_argument("--output", required=True, help="输出excel文件路径")
    parser.add_argument("--lang", default="Chinese", help="源语言")
    parser.add_argument("--maxerr", type=int, default=3, help="当错误数达到阈值，提前中止")
    parser.add_argument("--startRow", type=int, default=4, help="翻译内容起始行数")
    parser.add_argument("--saveInterval", type=int, default=5, help="每翻译一定数量条目，就会把当前进度存进临时文件")
    args = parser.parse_args()
    if not os.path.exists(args.input):
        print(f"Error: 输入Excel文件 {args.input} 不存在")
        exit(1)
    if os.path.exists(args.output) and is_file_opened(args.output):
        print(f"Error: 输出文件 {args.output} 不可写")
        exit(1)
    run(args.input, args.output, args.lang, args.maxerr, args.startRow, args.saveInterval)

